package com.etl.core.handler;

/**
 * @Author：ShenJiaFeng
 * @Package：com.baili.healthcommoncore.domain.handler
 * @Project：baili-health-cloud
 * @name：GlobalExceptionHandler
 * @Date：2024/5/24 21:20
 */
import com.alibaba.fastjson2.JSONObject;
import com.etl.core.domain.R;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.xml.bind.ValidationException;
import java.util.stream.Collectors;

/**
 * 全局异常定义
 */
@Log4j2
@RestControllerAdvice
@Configuration
public class GlobalExceptionHandler {
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<String> runtimeException(MethodArgumentNotValidException exception) {
        log.error("请求异常：[{}]", exception.getMessage(), exception);
        return R.fail(
                JSONObject.toJSONString(
                        exception.getBindingResult().getAllErrors()
                                .stream()
                                .map(ObjectError::getDefaultMessage)
                                .collect(Collectors.toList())
                )
        );
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public R<String> illegalArgumentExceptionHandler(IllegalArgumentException exception) {
        log.error("请求异常：[{}]", exception.getMessage(), exception);
        return R.fail(exception.getMessage());
    }

    @ExceptionHandler(value = RuntimeException.class)
    public R<String> runtimeExceptionExceptionHandler(RuntimeException exception) {
        log.error("请求异常：[{}]", exception.getMessage(), exception);
        return R.fail(exception.getMessage());
    }

    @ExceptionHandler(value = ValidationException.class)
    public R<String> validExceptionHandler(ValidationException exception) {
        log.error("请求异常：[{}]", exception.getMessage(), exception);
        return R.fail(exception.getMessage());
    }

//    @ExceptionHandler(value = Exception.class)
//    public Result<String> validExceptionHandler(Exception exception) {
//        log.error("请求异常：[{}]", exception.getMessage(), exception);
//        return Result.error(exception.getMessage());
//    }

}
